<template>
  <Dialog :appDialog="appDialog">
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="100px" class="formData">
      <el-form-item label="上传表格">
        <div class="upload-content">
          <ZWUpload v-if="!formData.fileData.name" class="upload" :upInfo="picInfo" @submit="getFileListFun" />
          <div v-if="!formData.fileData.name" class="upload-box">
            <el-icon style="font-size: 20px"><plus /></el-icon>
            <span>上传Excel文件</span>
          </div>
          <div class="upload-file-box" v-if="formData.fileData.name">
            <div class="left">
              <img src="@/assets/image/customer/xls_icon.png" alt="" />
              <span>{{ formData.fileData.name }}</span>
            </div>
            <img @click="delFile" class="right" src="@/assets/image/customer/close_icon.png" alt="" />
          </div>
        </div>
        <span class="download" @click="downloadDome">下载Excel模版</span>
        <div class="upload-desc"> 请按照模板的要求上传客户资料，若有重复手机号或空行将会自动过滤，以及不符合规范的填写格式，上传后直接显示”--“ </div>
      </el-form-item>
      <el-form-item label="选择客户标签" prop="cust_tag_ids">
        <div class="tabs-box" v-if="tabs.length > 0">
          <div v-for="(item, index) in tabs" :key="index"
            >{{ item.name }}<el-icon @click="delTab(index)" style="font-size: 16px" class="del-icon"><close /></el-icon
          ></div>
        </div>
        <el-button @click="openBatchLabel">请选择标签</el-button>
      </el-form-item>
      <el-form-item label="选择员工" prop="work_user_ids">
        <div class="yuangong-list">
          <div v-for="(item, index) in yuangongList" :key="item.name">
            <img src="@/assets/image/customer/renyuan_icon.png" alt="" />
            <span>{{ item.name }}</span>
            <img @click="delYuangong(index)" class="del_icon" src="@/assets/image/customer/close_icon.png" alt="" />
          </div>
        </div>
        <el-button @click="openDepart">请选择员工</el-button>
        <div class="yuangong-desc upload-desc"> 客户将被平均分配给指定的员工。注意：已存在的客户指派的员工将不会被重新指派 </div>
      </el-form-item>
    </el-form>

    <ZWDepart ref="DepartRef" @submit="getZWDepartData" />

    <!-- 批量标签弹框 -->
    <BatchLabel ref="BatchLabelRef" @save="getLabelFun" />
  </Dialog>
</template>

<script lang="ts" setup>
  import BatchLabel from '@/components/BatchLabel.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import Dialog from '@/components/Dialog.vue'
  import ZWUpload from '@/components/ZWUpload.vue'
  import { inputCustomer } from '@/api/customerCenter'
  import { downloadCustTemplate } from '@/api/customerCenter/groupManage'

  import { ElMessage } from 'element-plus'
  import { ref, reactive, watch, computed } from 'vue'
  import type { ElForm } from 'element-plus'
  import { getSetionId } from '@/utils/utils'
  import { useStore } from '@/store'

  const emit = defineEmits(['save', 'cancel'])

  type FormInstance = InstanceType<typeof ElForm>
  const ruleFormRef = ref<FormInstance>()
  const BatchLabelRef = ref({})
  const store = useStore()
  const tabs = ref([])
  const DepartRef = ref({})
  const picInfo = ref({
    type: 5,
    label: '文件',
    prop: 'files',
    multiple: false,
    limitSize: 20,
    limitNum: 1,
    acceptFile: '.xls,.xlsx',
    files: []
  })
  const rules = [{ cust_tag_ids: { required: true, trigger: 'blur', message: '请选择标签' } }, { work_user_ids: { required: true, trigger: 'blur', message: '请选择分配员工' } }]
  let formData = ref({})
  let yuangongList = ref([])

  // 初始化formData
  const initFormData = () => {
    ruleFormRef.value?.resetFields()
    formData.value = {
      fileData: {},
      cust_tag_ids: [], //标签id
      work_user_ids: [] //当前选择的员工id
    }
  }

  // 打开选择标签弹框
  const openBatchLabel = () => {
    BatchLabelRef.value.dialogVisible = true
    BatchLabelRef.value.dialogData.labelChooseType = 1
    if (tabs.value.length > 0) {
      BatchLabelRef.value.chooseDataArr = tabs.value
    }
  }
  // 获取选择的标签
  const getLabelFun = (val: object) => {
    console.log(val.idList, 5555)
    formData.value.cust_tag_ids = val.idList
    tabs.value = val.data
  }
  // 删除选中的标签
  const delTab = (index: number) => {
    tabs.value.splice(index, 1)
  }

  // 关闭弹框
  const cancelHandel = () => {
    appDialog.value.visible = false
    emit('cancel')
  }

  // 保存
  const submitHandel = () => {
    let { fileData, cust_tag_ids, work_user_ids } = formData.value
    if (!fileData.name || !work_user_ids.length) {
      ElMessage.error('请补充客户资料')
      return
    }
    let param = new FormData()
    param.append('cust_import', fileData.raw)
    param.append('cust_tag_ids', cust_tag_ids)
    param.append('work_user_ids', work_user_ids)
    inputCustomer(param)
      .then((r: object) => {
        emit('save', true)
        cancelHandel()
      })
      .catch((e: object) => {})
  }

  // 获取上传的文件
  const getFileListFun = (val: any) => {
    console.log(val, 5555)
    formData.value.fileData = val
  }

  let appDialog = ref({
    visible: false,
    title: '导入客户',
    width: '620px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
  })

  watch(
    () => appDialog.value.visible,
    (val) => {
      if (val) {
        initFormData()
        yuangongList.value = []
        tabs.value = []
      }
    }
  )

  //打开新建选择人
  const openDepart = () => {
    DepartRef.value.departVisble = true
    DepartRef.value.appDialog.chooseArr = yuangongList.value.map((it) => {
      return it.id
    })
    DepartRef.value.appDialog.isInit = true
  }

  const departInfo = computed(() => {
    return store.getters['content/depart']
  })

  // 获取选中的人员
  const getZWDepartData = (val: any) => {
    console.log(val, 555)
    yuangongList.value = val
    formData.value.work_user_ids = getSetionId('id', val.value)
  }

  // 删除选中的员工
  const delYuangong = (index: number) => {
    yuangongList.value.splice(index, 1)
  }

  // 下载dome
  const downloadDome = () => {
    downloadCustTemplate({}).then((r:any)=>{
      var a = document.createElement('a');
      // 获取文件名fileName
      a.href = r.file_url;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }).catch((e:any)=>{
      console.log(e)
    })
  }

  // 删除当前上传的文件
  const delFile = () => {
    formData.value.fileData = {}
    picInfo.value.files = []
  }

  defineExpose({
    appDialog
  })
</script>

<style lang="scss" scoped>
  .formData {
    max-height: 50vh;
    overflow-y: scroll;
    padding: 12px 30px 50px 0;
    .upload-content {
      overflow: hidden;
      box-sizing: border-box;
      position: relative;
      display: inline-block;
      vertical-align: middle;
      width: 180px;
      height: 36px;
      border: 1px solid #eaeaea;
      margin-bottom: 6px;
      .upload {
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 9;
        opacity: 0;
      }
      .upload-box {
        position: relative;
        width: 180px;
        height: 36px;
        border-radius: 4px;
        line-height: 36px;
        text-align: center;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #969696;
        display: flex;
        align-items: center;
        justify-content: center;
        span {
          margin-left: 9px;
        }
      }
      .upload-file-box {
        display: flex;
        justify-content: space-between;
        border-radius: 4px;
        border: 1px solid #eaeaea;
        width: 180px;
        height: 36px;
        line-height: 36px;
        .left {
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          color: #33302d;
          padding-left: 10px;
          span {
            vertical-align: middle;
          }
          img {
            margin-top: 8px;
            width: 20px;
            height: 20px;
            margin-right: 4px;
            vertical-align: middle;
          }
        }
        .right {
          cursor: pointer;
          width: 12px;
          height: 12px;
          margin-right: 10px;
          margin-top: 12px;
        }
      }
    }

    .download {
      font-size: 12px;
      font-family: STHeitiSC-Light, STHeitiSC;
      color: #ff6b00;
      margin-left: 10px;
      cursor: pointer;
    }
    .upload-desc {
      margin-top: 6px;
      background: #f9f9f9;
      border-radius: 1px;
      font-size: 12px;
      font-family: STHeitiSC-Light, STHeitiSC;
      color: #696969;
      padding: 4px 8px;
      line-height: 16px;
    }
    .tabs-box {
      margin-bottom: 7px;
      div {
        display: inline-block;
        background: #fffaf9;
        border-radius: 2px;
        border: 1px solid #ffc69e;
        justify-content: center;
        align-items: center;
        padding: 0 4px;
        line-height: 22px;
        height: 22px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #ff6b00;
        margin-right: 10px;
        margin-bottom: 7px;
        .del-icon {
          margin-left: 8px;
          vertical-align: middle;
          cursor: pointer;
        }
      }
    }
    .yuangong-list {
      div {
        display: inline-block;
        vertical-align: middle;
        background: #fffaf9;
        border-radius: 1px;
        margin-right: 10px;
        margin-bottom: 10px;
        padding: 4px 8px;
        line-height: 22px;
        box-sizing: border-box;
        img {
          width: 10px;
          height: 12px;
        }
        .del_icon {
          width: 12px;
          height: 12px;
          cursor: pointer;
        }
        span {
          margin: 0 10px;
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          color: #35383a;
        }
      }
    }
  }
  .formData::-webkit-scrollbar {
    display: none;
  }
</style>

<style>
  .upload-content .el-upload {
    display: block !important;
  }

  .upload-content .el-form-item__content {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
</style>
